import {baseUrl} from "@/config/env";

const srtReplaceAll = new RegExp("//", "gi");

export function formatUrl(url = "") {
    if (/^http:\/\//.test(url)) return url;
    if (/^https:\/\//.test(url)) return url;
    if (url.startsWith("/")) {
        url = url.substring(1);
    }
    let startBaseUrl = baseUrl
    if (startBaseUrl.startsWith("/")) {
        startBaseUrl = startBaseUrl.substring(1);
    }
    if (url.startsWith(startBaseUrl + "/")) {
        url = startBaseUrl.substring((startBaseUrl + "/").length)
    }
    if (url) {
        url = url.replace(srtReplaceAll, "/")
    }
    url = "/" + startBaseUrl + "/" + url;
    return url;
}

function getAvatar(data,def='/img/logo.png') {

    if (!data || data.length < 1) {
        return def
    }
    if (typeof data === 'string') {
        try {
            data = JSON.parse(data)
        } catch (e) {
            return def;
        }
    }
    if (typeof data === 'string') {
        return formatUrl(data);
    }
    if (Array.isArray(data) && data.length > 0) {
        return formJsonIcon(data[0], key, def)
    }
    if (data[key]) {
        return formatUrl(data[key])
    }
}

const userTools = {}
export default userTools